(function($) {
    $.fn.address = function(opt) {
        var opts = $.extend({
            url:"Area.xml",
            pn:"province",
            cin:"city",
            con:"country",
            attrName:"name",
            attrValue:"value",
            countryChange:function(){
            }
        },opt||{});
        //定义一个变量指向this ，方便在闭包中处理
        var target = this;
        opts.ps = $("<select id='province'><option>请输入省份</option></select>");
        opts.cis = $("<select id='city'><option>请输入市区</option></select>");
        opts.cos = $("<select id='country'><option>请输入县份</option></select>");

        //通过Ajax加载文件 并且初始化所有的xml节点
        opts.areaXml;
        $.get(opts.url,function(data){
            opts.areaXml = data;
            setAddress();
        });
        function setAddress() {
            //1.创建相应的省份节点
            setupNode(opts.pn,opts.ps);
            opts.ps.change(function(){
                opts.cos.find("option:gt(0)").remove();
                opts.cis.find("option:gt(0)").remove();
                setupNode(opts.pn+"[value='"+$(this).val()+"'] "+opts.cin,opts.cis);
            });
            opts.cis.change(function() {
                opts.cos.find("option:gt(0)").remove();
                setupNode(opts.cin+"[value='"+$(this).val()+"'] "+opts.con,opts.cos);
            });
            opts.cos.change(opts.countryChange);
            target.append($("<span class='address_c'></span>").append(opts.ps));
            target.append($("<span class='address_c'></span>").append(opts.cis));
            target.append($("<span class='address_c'></span>").append(opts.cos));
        }
        function setupNode(path,node) {
            $(opts.areaXml).find(path).each(function() {
                node.append(createNode(this));
            });
        }
        function createNode(obj) {
            return "<option value='"+$(obj).attr(opts.attrValue)+"'>"+$(obj).attr(opts.attrName)+"</option>";
        }
        return this;
    };
})(jQuery)
